/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.worlds.object;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import net.worlds.AssetManager;
import net.worlds.WorldsException;
import net.worlds.Main;
import net.worlds.PropChangeHandler;
import net.worlds.Util;
import net.worlds.input.InputState;
import net.worlds.lua.Event;
import net.worlds.ui.edge.EActionListener;
import net.worlds.ui.edge.EButton;
import org.jbox2d.common.Vec2D;


public class UIImageButton extends UIComponent{
    private BufferedImage image;
    private BufferedImage nullImage;
    public UIImageButton() throws WorldsException
    {
        super("UIImageButton");
        try {
            nullImage = AssetManager.loadImage("resource://null.png", "resource://null.png");
            component = new EButton(nullImage);
        } catch (IOException ex) {
            component = new EButton("Button");
        }
        ((EButton)component).setActionListener(new EActionListener()
        {
            @Override
            public void actionPerformed() {
                if(Main.isClient())
                {
                  Main.getClient().sendButtonClick(UIImageButton.this, InputState.mouseButton, InputState.mouseX, InputState.mouseY);
                }
                getEvent("MouseDown").fire(new Object[]{InputState.mouseButton, new Vec2D(InputState.mouseX, InputState.mouseY)});
            }
        });
        addPropChangeHandler("Image", new PropChangeHandler()
        {
            @Override
            public void handle(Object oldValue, final Object value) throws WorldsException {
                Util.performRequestWithCallback(new Runnable()
                {
                    public void run() {
                        try {
                            image = AssetManager.loadImage(value.toString(), value.toString());
                        } catch (IOException ex) {
                            image = nullImage;
                        }
                    }
                },
                new Runnable()
                {
                    public void run() {
                        ((EButton)component).setImage(image);
                    }
                });
            }
        });
        addPropChangeHandler("BackgroundColor", new PropChangeHandler()
        {
            @Override
            public void handle(Object oldValue, Object value) throws WorldsException {
                ((EButton)component).setColor(((Color)value));
            }
        });
        addPropChangeHandler("TextColor", new PropChangeHandler()
        {
            @Override
            public void handle(Object oldValue, Object value) throws WorldsException {
                ((EButton)component).setTextColor(((Color)value));
            }
        });
        addEvent("MouseDown", new Event(), "button (integer), screenPosition (Vec2D)");
    }
}
